// 管理账号信息
// 管理配置设置信息
const KEY_NAME = 'JOOLUN_';

const USER_KEY = KEY_NAME + 'USER_KEY';//个人信息
const PERMISSIONS_KEY = KEY_NAME + 'PERMISSIONS_KEY';//个人权限信息
const LOGIN_INFO = KEY_NAME + 'LOGIN_INFO';// 登录时加密后的数据，
const ACCESS_TOKEN = KEY_NAME + 'ACCESS_TOKEN'; // token
const REFRESH_TOKEN = KEY_NAME + 'REFRESH_TOKEN'; // token
const EXPIRES_IN = KEY_NAME + 'EXPIRES_IN'; // token有效期时间 秒
const SETTING_KEY = KEY_NAME + 'SETTING_KEY';//个人设置
const LOG_INFO_KEY = KEY_NAME + '_LOG_INFO_KEY';// 日志信息

const USER_ACCESS_TOKEN_KEY = KEY_NAME + 'USER_ACCESS_TOKEN';// token 接口返回的数据保存

// 获取个人信息
const getUser = function () {
    let ret =  uni.getStorageSync(USER_KEY);
	if(ret)
		return JSON.parse(ret);
	else
		return ret;
};
// 退出账号： 删除 所有的个人数据：包括 TOKEN,个人数据，登录数据，设置数据
const removeUser = function () {
	try {
		uni.removeStorageSync(USER_KEY);
		uni.removeStorageSync(ACCESS_TOKEN);
		uni.removeStorageSync(LOGIN_INFO);
		uni.removeStorageSync(REFRESH_TOKEN);
		uni.removeStorageSync(SETTING_KEY);
		uni.removeStorageSync(USER_ACCESS_TOKEN_KEY);
		uni.removeStorageSync(PERMISSIONS_KEY);
		uni.removeStorageSync(LOG_INFO_KEY);
		uni.removeStorageSync('has_read_privacy');
	} catch (e) {
		console.log(e)
	}
};
// 获取 最近一次登录时返回的数据
const getLoginAccessToken = function () {
	const loginAccessTokenInfo = uni.getStorageSync(USER_ACCESS_TOKEN_KEY);
    return loginAccessTokenInfo?JSON.parse(loginAccessTokenInfo):null;
};
// 获取本次登录token
const getAccessToken = function () {
    return uni.getStorageSync(ACCESS_TOKEN);
};

// 获取本次登录 Refresh token
const getRefreshToken = function () {
    return uni.getStorageSync(REFRESH_TOKEN);
};
const removeRefreshToken = function () {
    return uni.removeStorageSync(REFRESH_TOKEN);
};

// 保存登录Token信息
const saveAccessToken = function(response) {
	try {
		response.loginTime = new Date().getTime();//将最近登录的时间存入
		response.expires_in = response.loginTime + (response.expires_in*1000);
		uni.setStorageSync(ACCESS_TOKEN, response.access_token);
		uni.setStorageSync(REFRESH_TOKEN, response.refresh_token);
		uni.setStorageSync(EXPIRES_IN, response.expires_in);
		uni.setStorageSync(USER_ACCESS_TOKEN_KEY, JSON.stringify(response));
		let app = getApp();
		app.globalData.access_token = response.access_token;
		app.globalData.username = response.username;
		app.globalData.user_id = response.user_id;
		app.globalData.tenant_id = response.tenant_id;
		app.globalData.expires_in = response.expires_in;
	} catch (e) {
		console.log('save login token info error:' + e);
	}
}
// 获取登录信息
const getLoginInfo = function () {
	const loginInfo = uni.getStorageSync(LOGIN_INFO);
    return loginInfo?JSON.parse(loginInfo):null;
};
// 保存 登录信息
const saveLoginInfo = function(info) {
	try {
		uni.setStorageSync(LOGIN_INFO, JSON.stringify(info));
	} catch (e) {
		console.log('save user info error:' + e);
	}
};
// 获取 用户权限
const getUserPermissions = function () {
	const info = uni.getStorageSync(PERMISSIONS_KEY);
    return info?JSON.parse(info):null;
};
// 保存 用户权限
const saveUserPermissions = function(info) {
	try {
		let app = getApp();
		const list = {}
		  for (let i = 0; i < info.length; i++) {
			list[info[i]] = true
		  }
		app.globalData.permissions = list;
		uni.setStorageSync(PERMISSIONS_KEY, JSON.stringify(info));
	} catch (e) {
		console.log('save user info error:' + e);
	}
};

// 暂时无用（保存多账号登录）
const addUser = function (userInfo) {
    let users = getUser();
}

// 保存100条最新的日志
const saveLogInfo = function(info){
	try{
		let app = getApp();
		if(!app.globalData.isDev)return;
		let logList = uni.getStorageSync(LOG_INFO_KEY);
		if(logList){
			let logListObject = JSON.parse(logList);
			if(logListObject.length>=100){
				logListObject.shift();
			}
			logListObject.push({
				time: getNowTime(),
				log: info
			});
			uni.setStorageSync(LOG_INFO_KEY, JSON.stringify(logListObject));
		} else {
			let logList = [];
			logList.push({
				time: getNowTime(),
				log: info
			});
			uni.setStorageSync(LOG_INFO_KEY, JSON.stringify(logList));
		}
	}catch(e){
		console.log('saveHttpLog error:'+ e);
	}
}

const getNowTime = ()=>{
	// 创建一个 Date 对象
	let now = new Date();
	// 获取年、月、日、小时、分钟、秒
	let year = now.getFullYear();     // 年
	let month = now.getMonth() + 1;   // 月（注意：月份从0开始，所以要加1）
	let day = now.getDate();          // 日
	let hour = now.getHours();        // 小时
	let minute = now.getMinutes();    // 分钟
	let second = now.getSeconds();    // 秒
	// 当前时间
	return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
}

// 获取保存的日志数据
const getLogInfo = function(e){
	try{
		let app = getApp();
		if(!app.globalData.isDev)return;
		let log = uni.getStorageSync(LOG_INFO_KEY);
		if(log){
			return JSON.parse(log);
		} else {
			return [];
		}
	}catch(e){
		console.log('getHttpLog error:'+ e);
	}
}
// 获取保存的日志数据
const removeLogInfo = function(){
	try{
		uni.removeStorageSync(LOG_INFO_KEY);
	}catch(e){
		console.log('getHttpLog error:'+ e);
	}
}
// 保存用户信息
const saveUserInfo = function(userInfo){
	try{
		uni.setStorageSync(USER_KEY, JSON.stringify(userInfo));
	}catch(e){
		console.log('save user info error:'+ e);
	}
}

// 获取个人设置信息
const getUserSetting = function () {
    let ret =  uni.getStorageSync(SETTING_KEY);
	if(ret)//有就返回，没有就用默认值
		return JSON.parse(ret);
	else{
		return {
			noticeSound: true,//消息通知的声音是否开启
		}
	}
}
// 移出个人设置信息
const removeUserSetting = function () {
	try {
		uni.removeStorageSync(SETTING_KEY);
	} catch (e) {
		console.log(e)
	}
}
// 保存配置信息
const saveUserSetting = function (settingInfo) {
    uni.setStorageSync(SETTING_KEY, JSON.stringify(settingInfo));
}

// 获取 Token到期时间
const getExpiresIn = function () {
	return uni.getStorageSync(EXPIRES_IN);
};
// 保存 Token到期时间
const saveExpiresIn = function(info) {
	try {
		uni.setStorageSync(EXPIRES_IN, info);
	} catch (e) {
		console.log('save EXPIRES_IN info error:' + e);
	}
};
export default {
	saveLoginInfo,
	getLoginInfo,
	saveAccessToken,
    getUser,
    addUser,
    removeUser,
	saveUserInfo,
	saveUserSetting,
	removeUserSetting,
	getUserSetting,
	getAccessToken,
	getRefreshToken,
	getLoginAccessToken,
	removeRefreshToken,
	getExpiresIn,
	saveExpiresIn,
	saveLogInfo,
	getLogInfo,
	removeLogInfo,
	saveUserPermissions,
	getUserPermissions,
}
